from typing import Dict, List

from flask import Blueprint, request
from common import helper
from common.helper import json_resp
from modules.amis.component.base import Option
from modules.amis.component.datainput import Radio, Radios, Switch
from modules.amis.component.layout import TabItem, Page, Tabs
from modules.datafaker.strategies import create_strategy_list, execute_strategy

datafaker_bp = Blueprint("datafaker", __name__)

strategy_list = create_strategy_list()


@datafaker_bp.route("/page")
def page():
    page_data = {
        "has_result": False
    }

    tab_input_param = TabItem(title="输入参数")
    tab_result = TabItem(title="结果", visibleOn="has_result")
    tab_output = TabItem(title="导出", visibleOn="has_result")
    tabs = Tabs(tabs=[tab_input_param, tab_result, tab_output])

    test = Radios(name="has_result", options=[
        Option(label="选中", value=True),
        Option(label="未选中", value=False)
    ])

    test2 = Switch(name="has_result", onText="显示", offText="隐藏")

    return json_resp(Page(enablePrint=True, data=page_data, body=[
        tabs,
        test2
    ]).render())


@datafaker_bp.route("/")
def index():
    return helper.success("success")


@datafaker_bp.route("/strategyList", methods=['POST'])
def strategyList():
    return helper.success(strategy_list)


@datafaker_bp.route("/fake", methods=['POST'])
def fake():
    """
    {
        "num": 100,
        "fieldList": [
            {
                "fieldName": "姓名",
                "fakeName": "city2",
                "rule": {
                    "fakeName": "city2"
                }
            }
        ]
    }
    :return:
    """
    data = request.json
    num: int = data['num']
    fieldList: List = data["fieldList"]

    result: List[List[Dict[str, object]]] = []
    for i in range(num):
        row_list: List[Dict[str, object]] = []
        for field in fieldList:
            field_name = field['fieldName']
            if helper.is_blank(field_name):
                continue

            fake_name: str = ''
            fake_lang = 'zh_CN'
            if 'fakeName' in field:
                fake_name = field['fakeName']
                if helper.is_blank(fake_name):
                    continue
            elif 'rule' in field:
                rule: Dict = field['rule']

                fake_name = rule['fakeName']
                if helper.is_blank(fake_name):
                    continue

                if 'lang' in rule and helper.is_not_blank(rule['lang']):
                    fake_lang = rule['lang']

            fake_result = execute_strategy(fake_name)
            row_list.append(
                {
                    "fieldName": field_name,
                    "data": fake_result
                }
            )
        result.append(row_list)

    return helper.success(result)
